package com.hmall.cart.listener;


import com.hmall.cart.service.ICartService;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;

/**
 * 使用RabbitMQ完成对购物车的清理
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ClearListener {
    private final ICartService cartService;
    /**
     * 定义topic类型交换机，命名为trade.topic
     * 定义消息队列，命名为cart.clear.queue
     * 将cart.clear.queue与trade.topic绑定，BindingKey为order.create
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.TRADE_CART_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name = MqConstants.TRADE_CART_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = MqConstants.TRADE_CART_KEY
    ))
    public void listenerClearCart(Message message , Set<Long> itemIds){
        Long userId = message.getMessageProperties().getHeader("userId");
        log.info("正在清理user_id为 :{} 的购物车数据",userId);
        UserContext.setUser(userId);
        cartService.removeByItemIds(itemIds);
    }
}
